﻿using System;
using System.Data;
using System.Linq;
using Business.dao.conf;
using Microsoft.Practices.Unity;

namespace Business.dao.utils
{


    public abstract class GenericDAOImpl<T> : IGenericDAO<T>
        where T : class
    {
        
        protected ContextoDB contexto;

        [Dependency]
        public ContextoDB
        Contexto { set { contexto = value; } }

        protected GenericDAOImpl()
        { }

        public T buscar(Object id)
        {
            return contexto.Set<T>().Find(id);
        }

        public T inserir(T t)
        {
            t = contexto.Set<T>().Add(t);
            contexto.SaveChanges();
            return t;
        }

        public T atualizar(T t)
        {
            contexto.Entry(t).State = EntityState.Modified;
            contexto.SaveChanges();
            return t;
        }

        public T anexarAoContexto(T t)
        {
            return contexto.Set<T>().Attach(t);
        }


        public void remover(Object id)
        {
            T item = contexto.Set<T>().Find(id);
            contexto.Set<T>().Remove(item);
            contexto.SaveChanges();
        }

        [PerfilSegurancaRequerido]
        public virtual IQueryable<T> listar()
        {
            return contexto.Set<T>().AsQueryable();
        }


        public T criar()
        {
            return contexto.Set<T>().Create();
        }


        public T atachar(T t)
        {
            return contexto.Set<T>().Attach(t);
        }

    }
}

